package com.yang.app.config;

import java.io.OutputStream;
import java.io.UnsupportedEncodingException;

import javax.servlet.http.HttpServletResponse;

public class RenderTool {

	
	private static final String JSON = "JSON";
	
	private static final String XML = "XML";
	
	private static final String UTF8 = "utf-8";
	
	private static final String HTML = "HTML";
	
	private static final String PLAIN = "PLAIN";
	
	private static final String JAVASCRIPT = "JAVASCRIPT";
	
	
	
	public static void sendJavaScript(HttpServletResponse response,String content){
		renderObj(response,JAVASCRIPT,content);
	}
	public static void sendJSON(HttpServletResponse response,String content){
		renderObj(response,JSON,content);
	}

	public static void sendXML(HttpServletResponse response,String content) {
		renderObj(response,XML,content);
	}
	
	public static void sendHTML(HttpServletResponse response,String content) {
		renderObj(response,HTML,content);
	}
	
	public static void sendPLAIN(HttpServletResponse response,String content) {
		renderObj(response,PLAIN,content);
	}
	public static synchronized void renderObj(HttpServletResponse response,String type,String content){
		response.setCharacterEncoding(UTF8);
		String encoding = response.getCharacterEncoding();
		String contentJsonType = "application/json; charset=utf-8";
		String contentXmlType =  "text/xml; charset=utf-8";
		String contentTextType = "text/plain; charset=utf-8";
		String contentHtmlType = "text/html; charset=utf-8";
		String contentJavaScriptType = "application/javascript; charset=utf-8";
		
		if(type.equals(JSON)){
			response.setContentType(contentJsonType);
		}
		if(type.equals(XML)){
			response.setContentType(contentXmlType);
		}
		if(type.equals(HTML)){
			response.setContentType(contentHtmlType);
		}
		if(type.equals(PLAIN)){
			response.setContentType(contentTextType);
		}
		if(type.equals(JAVASCRIPT)){
			response.setContentType(contentJavaScriptType);
		}
		
		OutputStream out = null;
		try {
			
			out = response.getOutputStream();
			out.write(content.getBytes(encoding));
			out.flush();
		} catch (UnsupportedEncodingException e) {
		} catch (Exception e) {
		}
	}
}
